package com.scs.application.modules.purchase.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.consts.SerialKeys;
import com.scs.application.core.entity.DataEntity;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.flow.FlowContext;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.*;
import com.scs.application.modules.base.entity.Matr;
import com.scs.application.modules.base.entity.Supplier;
import com.scs.application.modules.base.mapper.MatrMapper;
import com.scs.application.modules.base.mapper.SupplierMapper;
import com.scs.application.modules.base.util.CommonService;
import com.scs.application.modules.base.util.MatrPassUtil;
import com.scs.application.modules.cfg.utils.ParameterUtils;
import com.scs.application.modules.dept.mapper.ApplyAutoMapper;
import com.scs.application.modules.purchase.entity.Order;
import com.scs.application.modules.purchase.entity.OrderItem;
import com.scs.application.modules.purchase.entity.tpOrderDTO;
import com.scs.application.modules.purchase.enums.PoType;
import com.scs.application.modules.purchase.enums.PurchaseType;
import com.scs.application.modules.purchase.mapper.OrderItemMapper;
import com.scs.application.modules.purchase.mapper.OrderMapper;
import com.scs.application.modules.purchase.service.OrderItemService;
import com.scs.application.modules.purchase.service.OrderService;
import com.scs.application.modules.sys.entity.ScheduleJob;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.sys.properties.ResProperties;
import com.scs.application.modules.sys.service.ScheduleJobService;
import com.scs.application.modules.thirdparty.dto.*;
import com.scs.application.modules.thirdparty.service.MscmService;
import com.scs.application.modules.wm.entity.WorkOrder;
import com.scs.application.modules.wm.mapper.WorkOrderMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购订单 服务实现类
 * </p>
 */
@Slf4j
@Service
public class OrderServiceImpl extends BaseServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private MatrMapper matrMapper;

    @Autowired
    private MscmService mscmService;

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Lazy
    @Autowired
    private SchedulerFactoryBean scheduler;

    @Autowired
    private ResProperties resProperties;

    @Autowired
    private ApplyAutoMapper applyAutoMapper;

    @Autowired
    ScheduleJobService scheduleJobService;

    @Autowired
    MatrPassUtil matrPassUtil;

    @Override
    public boolean saveOrUpdate(Order entity) {
        if (StringUtils.isBlank(entity.getBusKey())) {
            entity.setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.PURCHASE_ORDER_KEY));
            entity.setRefTable("purchase_order");
        }
        return super.saveOrUpdate(entity);
    }


    @Override
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        List<OrderItem> orderItems = orderItemService.list(Wrappers.<OrderItem>query().in("order_id", idList));
        List<String> applyOrderIds = new ArrayList<>();
        for (OrderItem orderItem : orderItems) {
            if (StringUtils.isNotBlank(orderItem.getApplyItemId())) {
                CommonService.updateApplyItemStatus(orderItem.getApplyItemId(),true,"采购删除");
            }
            if (StringUtils.isNotBlank(orderItem.getApplyAutoId())) {
                applyOrderIds.add(orderItem.getApplyAutoId());
        }
        }
        orderItemMapper.delete(Wrappers.<OrderItem>query().in("order_id", idList));
        boolean removeCascadeByIds = super.removeCascadeByIds(idList);
        CommonService.updateApplyInfo(applyOrderIds,-1);
        return removeCascadeByIds;
    }

    @Override
    public Page<?> page(QueryContext context) {
        QueryWrapper wrapper = context.getWrapper();
        if (!UserUtils.isAdmin()) {
            // wrapper.eq("dept_id", UserUtils.currentUser().getOfficeId());
        }
        return super.page(context);
    }

    @Override
    protected void beforeHandleFlowChange(FlowContext flowContext, Order entity) {
        super.beforeHandleFlowChange(flowContext, entity);
        String buttonKey = flowContext.getButtonKey();
        List<OrderItem> orderItemList = orderItemMapper.selectList(Wrappers.<OrderItem>query().eq("order_id", flowContext.getBusId()));
        //采购订单流程控制--耗材禁用校验
        matrPassUtil.ckeckMatrPass("purchase",orderItemList.stream().map(OrderItem::getMatrId).collect(Collectors.toList()));
        // 提交审核，不允许空明细提交
        if ("submit".equalsIgnoreCase(buttonKey)) {
            Order order = baseMapper.selectById(flowContext.getBusId());
//            Integer count = orderItemMapper.selectCount(Wrappers.<OrderItem>query().eq("order_id", flowContext.getBusId()));
//            if (count == null || count == 0) {
            if (CollectionUtils.isEmpty(orderItemList)) {
                throw new BusinessException("订单%s请添加明细后提交" , order.getBusKey());
            }

            orderItemList.forEach(ob -> {
                //单品数量*单品价格 是否等于 合计金额
                if(UtilNum.mul(ob.getSkuQty(),ob.getSkuPrice()) != ob.getAmount())  {
                    ob.setAmount(UtilNum.mul(ob.getSkuQty(),ob.getSkuPrice()));
                    if (ob.getAmount() == 0) {
                        throw new BusinessException("有订单明细金额为0，不允许提交");
                    }
                    //单品数量*单品价格 是否等于 合计金额
                    orderItemService.updateById(ob);
                }
            });

            final double[] amountDtl = {0};
            orderItemList.forEach(item -> amountDtl[0] =UtilNum.sum(amountDtl[0],item.getAmount()));
            Order orderDb = this.getById(entity.getId());
            if (amountDtl[0] != orderDb.getAmount()) {
                orderDb.setAmount(amountDtl[0]);
                this.updateById(orderDb);
            }
        }

    }

    @Override
    protected void afterHandleFlowChange(FlowContext flowContext, Order entity) {
        super.afterHandleFlowChange(flowContext, entity);

        String buttonKey = flowContext.getButtonKey();
        entity = baseMapper.selectById(entity.getId());
        List<String> idList = new ArrayList<>();
        if ("pass".equalsIgnoreCase(buttonKey) && !entity.getFlagClosed()) {
            Integer count = orderItemMapper.selectCount(Wrappers.<OrderItem>query().eq("order_id", flowContext.getBusId()));
            if (count == null || count == 0) {
                throw new BusinessException("请添加明细后提交");
            }
            List<OrderItem> orderItemList = orderItemMapper.selectList(Wrappers.<OrderItem>query().eq("order_id", flowContext.getBusId()));
            //流程节点耗材校验--采购订单
            matrPassUtil.ckeckMatrPass("purchase", orderItemList.stream().map(OrderItem::getMatrId).collect(Collectors.toList()));
            List<Matr> matrList =  matrMapper.selectList(Wrappers.<Matr>query().isNull("mscm_code").in("id", orderItemList.stream().map(OrderItem :: getMatrId).collect(Collectors.toList())));

            if (matrList != null && matrList.size() >0) {
                throw new BusinessException("耗材【%s】未做供应商平台同步，请联系运营人员同步后，再审核订单",matrList.get(0).getName());
            }

            idList.add(entity.getId());

            this.pushOrder(idList, false);


            //更新需求明细状态
            orderItemList.stream().forEach(orderItem -> {
                CommonService.updateApplyItemStatus(orderItem.getApplyItemId(),false,null);
            });

        } else {
            List<OrderItem> orderItemList = orderItemMapper.selectList(Wrappers.<OrderItem>query().eq("order_id", flowContext.getBusId()));
            //更新需求明细状态
            orderItemList.stream().forEach(orderItem -> {
                CommonService.updateApplyItemStatus(orderItem.getApplyItemId(),false,null);
            });
        }
    }

    /*@Async
    private void asyncPushOrder(Order rawOrder) {
        List<OrderDTO> orderDTOS = this.buildMscmOrder(Lists.newArrayList(rawOrder));
        mscmService.pushOrder(orderDTOS);
    }*/


    @Override
    public String pushOrder(List<String> idList, Boolean flagExport) {

        String filePath = "";
        // 只推送已审核、未推送、未关闭的
        List<Order> orders = list(Wrappers.<Order>query()
                .in("id", idList)
                .eq("flag_closed", false)
                .eq("flag_pushed", false)
        );
        if (orders.isEmpty()) {
            throw new BusinessException("订单状态不支持推送，请检查！");
        }

        List<OrderDTO> mscmOrders = buildMscmOrder(orders);

        if(!ParameterUtils.isAllowInternet() && !flagExport) {
            return filePath;
        }
        if(ParameterUtils.isAllowInternet()) {
            mscmService.pushOrder(mscmOrders);
        } else if(flagExport){
            filePath = exportNeedSendPoList(mscmOrders);
        }

        update(Wrappers.<Order>update()
                .in("id", idList)
                .set("flag_pushed", true)
                .set("gmt_pushed", new Date())
        );

        CommonService.updateApplyInfo(idList,1);
        return filePath;
    }

    @Override
    public RestResult getNum(List<String> idList) {

        RestResult result = RestResult.ok("");
        String tpn = ParameterUtils.getTemporaryPurchaseNum();
        int tpNum = 0;
        if(tpn == "0"){
            return result;
        }
        tpNum = Integer.parseInt(tpn);
        List<tpOrderDTO> tpOrderDTOS =  this.baseMapper.getNum(idList, tpNum);
        if (tpOrderDTOS.isEmpty()) {
            return result;
        }
        for(tpOrderDTO tpOrderDTO : tpOrderDTOS){
            if(result.getMsg() == ""){
                result.setMsg("耗材" + tpOrderDTO.getMatrName() +  "已入库" + tpOrderDTO.getNum() + "次");
                continue;
            }
            result.setMsg(result.getMsg() + ", " + tpOrderDTO.getMatrName() +  "已入库" + tpOrderDTO.getNum() + "次");
        }
        List<String> ids = tpOrderDTOS.stream().map(o -> o.getMatrId()).collect(Collectors.toList());

        result.setData(ids);
        return result;
    }

    private List<OrderDTO> buildMscmOrder(List<Order> rawOrders) {
        List<OrderDTO> orderList = Lists.newArrayList();

        List<Supplier> suppliers = supplierMapper.selectBatchIds(rawOrders.stream().map(Order::getSupplierId).collect(Collectors.toSet()));
        Map<String, Supplier> supplierMap = suppliers.stream().collect(Collectors.toMap(DataEntity::getId, o -> o));

        for (Order order : rawOrders) {
            Supplier supplier = supplierMap.get(order.getSupplierId());
            if (supplier == null) {
                throw new BusinessException("供应商%s在当前系统中不存在，不支持推送", order.getSupplierName());
            }
            if (StringUtils.isBlank(supplier.getMscmCode())) {
                throw new BusinessException("供应商%s尚未维护MSCM系统标识，不支持进行推送", order.getSupplierName());
            }


            OrderDTO dto = new OrderDTO();
            dto.setPoCode(order.getBusKey()).setSourceKey(order.getId()).setRemark(order.getRemark())
                    .setIsConsignment(PoType.CONSIGNMENT.getValue().equals(order.getPoType()) ? "1" : "0")
                    .setIsOneThingOneYard(order.getFlagOmoc() ? "1" : "0").setPurchaseDate(order.getBusDate())
                    .setGmtRequireLatestDelivery(order.getDateLates()).setBuyerName(order.getBusUser())
                    .setSupplierKey(supplier.getMscmCode()).setSupplierName(order.getSupplierName()).setGmtAudited(DateUtils.localDateTime2Date(order.getFlowModified()))
                    .setWarehouseName(order.getWarehouseName()).setWarehouseKey(order.getWarehouseId()).setTotalAmount(order.getAmount())
                    .setDemandDeptId(order.getDeptIdDemand()).setDemandDeptName(order.getDeptNameDemand())
            .setPurchaseType(UtilCommon.getStr(order.getPurchaseType(),"matr")).setTemperature(order.getTemperature())
            ;
            dto.setMaterialTypeCode(PurchaseType.valueOf(dto.getPurchaseType().toUpperCase()).getCode());

            List<OrderItem> rawItems = orderItemMapper.selectList(Wrappers.<OrderItem>query().eq("order_id", order.getId()));
            if (dto.getPurchaseType().equals(PurchaseType.PACKAGE.getKey())) {
                //dto.setPackageName(rawItems.stream().filter(orderItem -> "1".equals(orderItem.getMatrType())).findFirst().orElseThrow(() -> new BusinessException("采购明细未查询到跟台包,请检查")).getMatrName());
            }
            dto.setCountDtl(rawItems.size());
            List<Matr> matrs = matrMapper.selectBatchIds(rawItems.stream().map(OrderItem::getMatrId).collect(Collectors.toSet()));
            Map<String, Matr> matrMap = matrs.stream().collect(Collectors.toMap(DataEntity::getId, o -> o));


            List<OrderDTO.OrderItemDTO> items = Lists.newArrayListWithExpectedSize(rawItems.size());
            List<OrderItem> orderItemList = rawItems.stream().filter(orderItem -> "0".equals(orderItem.getMatrType())).collect(Collectors.toList());
            for (OrderItem rawItem : orderItemList) {
                Matr matr = matrMap.get(rawItem.getMatrId());

                OrderDTO.OrderItemDTO item = new OrderDTO.OrderItemDTO();
                item.setPoId(rawItem.getOrderId())
                        .setFlagWhole(ParameterUtils.flagWhole())
                        .setMaterialName(rawItem.getMatrName())
                        .setMaterialSpec(rawItem.getMatrSpec())
                        .setMaterialSpecId(rawItem.getMatrId())
                        .setMaterialCode(matr.getMscmCode())
                        .setCertificateNo(matr.getCertificateNo())
                        .setPackageRate(rawItem.getPackageRate()).setPackageUnit(rawItem.getPackageUnit())
                        .setSkuQty(rawItem.getSkuQty()).setSkuUnit(rawItem.getSkuUnit())
                        .setSkuPrice(rawItem.getSkuPrice()).setSubtotalAmount(rawItem.getAmount())
                        .setDeliveredQty(0.0).setDeliveredAmount(0.0).setBidNo(matr.getBidno())
                        .setManufacturerName(matr.getMfgName()).setSourceKey(rawItem.getId()).setRemark(rawItem.getRemark());
                items.add(item);
            }
            //测试数量不一致
//            items = items.subList(0, items.size()-2);
            dto.setItems(items);
            orderList.add(dto);
        }


        return orderList;
    }

    @Override
    public void closeOrder(List<String> idList, String reason,int flagDeliveryClose,String user) {

        // 已关闭订单不支持再次关闭
        List<Order> orders = list(Wrappers.<Order>query()
                .in("id", idList)
                .eq("flag_closed", false)
        );
        if (orders.isEmpty()) {
            return;
        }

        // todo 已入库 不允许关闭
        for (Order order : orders) {
            //已推送的订单
            if(order.getFlagPushed()){
                asyncCloseOrder(order.getBusKey(), reason,flagDeliveryClose,order.getBusUser());
            }

            update(Wrappers.<Order>update()
                    .eq("id", order.getId())
                    .set("flag_closed", true)
                    .set("flow_status", GlobalConsts.FLOW_CLOSE_VALUE)
                    .set("flow_close_remark",reason)
                    .set("closed_reason", reason)
                    .set("gmt_closed", new Date())
                    .set("close_user", UserUtils.currentUser().getName())
            );
//            if(!"end".equals(order.getFlowStatus())){
//                this.update(Wrappers.<Order>update().set("flow_status","end").eq("id",order.getId()));
//            }


            List<OrderItem> orderItemList = orderItemMapper.selectList(Wrappers.<OrderItem>query().eq("order_id", order.getId()));
            //更新需求明细状态
            orderItemList.stream().forEach(orderItem -> {
                CommonService.updateApplyItemStatus(orderItem.getApplyItemId(),false,null);
            });
        }
        CommonService.updateApplyInfo(idList,1);
    }

    @Override
    public void closeOrder(List<String> orderIdList, List<String> applyItemIdList, String reason,int flagDeliveryClose,String user) {

        List<OrderItem> items = orderItemService.list(Wrappers.<OrderItem>query()
                .in("apply_item_id", applyItemIdList)
                .eq("flag_close", false));
        if (items.isEmpty()) {
            return;
        }
        // 已关闭订单不支持再次关闭
        List<Order> orders = list(Wrappers.<Order>query()
                .in("id", items.stream().map(OrderItem :: getOrderId).distinct().collect(Collectors.toList()))
                .eq("flag_closed", false)
        );
        if (orders.isEmpty()) {
            return;
        }

        // todo 已入库 不允许关闭
        for (Order order : orders) {
            if((GlobalConsts.FLOW_END_VALUE.equals(order.getFlowStatus()) || GlobalConsts.FLOW_CONFIRM_VALUE.equals(order.getFlowStatus()))){
                continue;//如果采购订单是结束状态
            }
            //已推送的订单
            /*if(order.getFlagPushed()){
                asyncCloseOrder(order.getBusKey(), reason,flagDeliveryClose,order.getBusUser());
            }*/
            //items.stream().filter(item -> order.getId().equals(item.getOrderId())).collect(Collectors.toList());
            List<OrderItem> orderItemList = orderItemMapper.selectList(Wrappers.<OrderItem>query().eq("order_id", order.getId()).eq("flag_close", 0));
            if (!CollectionUtils.isEmpty(orderItemList)) {
                List<OrderItem> unCloseItems = orderItemList.stream().filter(orderItem -> applyItemIdList.contains(orderItem.getApplyItemId())).collect(Collectors.toList());
                Double unCloseAmount = unCloseItems.stream().mapToDouble(OrderItem::getAmount).sum();

                Boolean orderClose = false;
                String flowStatus = order.getFlowStatus();
                if (order.getAmount().compareTo(unCloseAmount) == 0) { //需要同时关闭采购主单
                    orderClose = true;
                    flowStatus = GlobalConsts.FLOW_CLOSE_VALUE;

                } else {
                    unCloseAmount = order.getAmount() - unCloseAmount;
                }
                orderItemService.update(Wrappers.<OrderItem>update()
                        .eq("order_id", order.getId()).in("id",unCloseItems.stream().map(OrderItem :: getId).collect(Collectors.toList()))
                        .set("flag_close", true)
                        .set("close_remark",reason)
                        .set("gmt_modified", new Date())
                        .set("modifier", UserUtils.currentUser().getName()));

                update(Wrappers.<Order>update()
                        .eq("id", order.getId())
                        .set("flag_closed", orderClose)
                        .set("flow_status", flowStatus)
                        .set("amount",unCloseAmount)
                        .set("flow_close_remark",reason)
                        .set("closed_reason", reason)
                        .set("gmt_closed", new Date())
                        .set("close_user", UserUtils.currentUser().getName())
                );

                //更新需求明细状态
                orderItemList.stream().forEach(orderItem -> {
                    CommonService.updateApplyItemStatus(orderItem.getApplyItemId(),false,null);
                });
            }

        }
        CommonService.updateApplyInfo(orderIdList, 1);
    }

    @Override
    public Integer findThisWeekPurchaseCount() {
        Date beginDate = DateUtils.parse(DateFormatUtils.format(DateUtils.getFirstDayOfWeek(new Date()),"yyyy-MM-dd 00:00:00"));
        Integer count = this.baseMapper.selectCount(Wrappers.<Order>query().gt("gmt_create", beginDate));
        return count;
    }

    @Override
    public String pullOrderStatus() {
        // 拉取mscm订单
        // 取调度任务的上次任务执行时间
        String beginDate = null;
        beginDate  = scheduleJobService.getLastSuccessDate("orderServiceImpl.pullOrderStatus()");
        if(beginDate == null){
            beginDate = DateUtils.format(new Date(), "yyyy-MM-dd 00:00:00");
        }
        //查询spd未入库已审核通过的订单
        List<String> ordersspd = list(Wrappers.<Order>query().eq("status_in",0).eq("flow_status","end"))
                .stream().map(o ->o.getBusKey()).collect(Collectors.toList());

        List<OrderStatusDTO> orderDTOS = mscmService.pullOrderStatus(ordersspd, beginDate);
        if (orderDTOS == null || orderDTOS.isEmpty()) {
            return "没有可拉取状态的订单";
        }
        log.info("从MSCM系统中拉取到{}个订单", orderDTOS.size());
        // 查出spd对应订单
        List<String> keys = orderDTOS.stream().map(o -> o.getSourceKey()).collect(Collectors.toList());
        List<Order> orders = this.list(Wrappers.<Order>query().in("id", keys));
        Map<String, OrderStatusDTO> dtoMap = orderDTOS.stream().collect(Collectors.toMap(o -> o.getSourceKey(), o -> o, (o1, o2) -> o1));

        // 修改订单状态
        List<Order> result = Lists.newArrayListWithCapacity(orders.size());
        for (Order oldOrder : orders) {
            OrderStatusDTO orderDTO = dtoMap.get(oldOrder.getId());
            Order newOrder = new Order();
            newOrder.setId(oldOrder.getId());
            // 是否关闭
            if (orderDTO.getIsClosed() == 1){
                newOrder.setFlagClosed(true);
            }
            // 供应商待确认
            if (orderDTO.getStatus() == 2){
                newOrder.setSyncStatus(GlobalConsts.OrderSyncStatus.UN_CONFIRM);
            }
            // 订单待发货
            if (orderDTO.getStatus() == 3){
                newOrder.setSyncStatus(GlobalConsts.OrderSyncStatus.UN_DELIVERY);
            }
            // 订单已发货 或 已完成
            if (orderDTO.getStatus() == 4 || orderDTO.getStatus() == 9){
                newOrder.setSyncStatus(GlobalConsts.OrderSyncStatus.DELIVERED);
                List<WorkOrder> workOrders = workOrderMapper.selectList(Wrappers.<WorkOrder>query()
                        .eq("purchase_order_id", oldOrder.getId()));
                double amount = 0d;
                if (workOrders != null && workOrders.size() > 0) {
                    amount = workOrders.stream().mapToDouble(o -> o.getAmount()).sum();
                }
                Double orderAmount = oldOrder.getAmount();
                if (amount == 0d) {
                    newOrder.setStatusIn(GlobalConsts.OrderStatusIn.UN_IN);
                }
                else if (amount < orderAmount){
                    newOrder.setStatusIn(GlobalConsts.OrderStatusIn.PART_IN);
                }
                else if (amount == orderAmount){
                    newOrder.setStatusIn(GlobalConsts.OrderStatusIn.ALL_IN);
                }
            }
            result.add(newOrder);
        }
        // 更新状态
        this.updateBatchById(result);
        return "拉取订单数量："+orderDTOS.size();
    }

    @Override
    public OrderQRCodeDTO printOrderQRCode(String orderId) throws Exception {
        Order order = this.getById(orderId);

        if (order.getFlagClosed()||order.getFlagPushed()){
            throw new BusinessException("采购订单已关闭或者已推送，无需打印");
        }
        List<OrderDTO> mscmOrders = buildMscmOrder(Collections.singletonList(order));

        return printOrderQRCode(mscmOrders.get(0));
    }

    @Async
    public void asyncCloseOrder(String orderKey, String reason, int flagDeliveryClose, String user) {
        mscmService.closeOrder(orderKey, reason, flagDeliveryClose, user);
    }

    /**
     * 导出待发送订单
     * @returns
     */
    public String exportNeedSendPoList(List<OrderDTO> mscmOrders){
        if(mscmOrders == null || mscmOrders.size() == 0) {
            return null;
        }
        FileUtils.mkdirs(resProperties.getRealPath() + "download/po/");
        String fileFullName = resProperties.getRealPath() + "download/po/" + serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.PO_EXPORT_KEY) + ".txt";
        FileUtils.writeTxtFile(fileFullName, JSON.toJSONString(mscmOrders, SerializerFeature.PrettyFormat));
        return fileFullName.substring(resProperties.getRealPath().length());
    }

    public OrderQRCodeDTO printOrderQRCode(OrderDTO orderDTO) throws Exception {
        OrderMainDTO orderMainDTO = new OrderMainDTO();
        OrderQRCodeDTO orderQRCodeDTO = new OrderQRCodeDTO();
        BeanUtils.copyProperties(orderDTO, orderMainDTO);
        String toJSONString = JSON.toJSONString(orderMainDTO);
        String zipMain = UtilJavax.zip(toJSONString);
        orderQRCodeDTO.setMainOrder(zipMain);
        List<OrderDTO.OrderItemDTO> mscmDtoItems = orderDTO.getItems();
        List<ItemCodeDTO> dtoItems = new ArrayList<>();
        for (OrderDTO.OrderItemDTO dtoItem : mscmDtoItems) {
            ItemCodeDTO itemCodeDTO = new ItemCodeDTO();
            BeanUtils.copyProperties(dtoItem, itemCodeDTO);
            dtoItems.add(itemCodeDTO);
}
        int pageSize = 3;
        int qrCodeCount = 1;
        int resultSize = dtoItems.size();
        if (resultSize > pageSize) {
            qrCodeCount = (resultSize % pageSize == 0 ? resultSize / pageSize : resultSize / pageSize + 1);
        }
        List<OrderQRCodeDTO.QRCodeItemDTO> result = Lists.newArrayListWithCapacity(resultSize);
        OrderQRCodeDTO.QRCodeItemDTO qrCodeItemDTOMain = new OrderQRCodeDTO.QRCodeItemDTO();
        qrCodeItemDTOMain.setItemOrder(zipMain);
        qrCodeItemDTOMain.setType("qrcode");
        qrCodeItemDTOMain.setText("主单据");
        result.add(qrCodeItemDTOMain);
        // 将数据转成JSON字符串，压缩后返回
        for (int i = 0; i < qrCodeCount; i++) {
            OrderQRCodeDTO.QRCodeItemDTO qrCodeItemDTO = new OrderQRCodeDTO.QRCodeItemDTO();
            int start = i * pageSize;
            int end = Math.min((i + 1) * pageSize, resultSize);

            List<ItemCodeDTO> listZip = dtoItems.subList(start, end);
            String base64EncodeItem = UtilJavax.zip(JSON.toJSONString(listZip));
            qrCodeItemDTO.setItemOrder(base64EncodeItem);
            qrCodeItemDTO.setType("qrcode");
            int i1 = start + 1;
            qrCodeItemDTO.setText("序号"+i1+"到"+end);
            result.add(qrCodeItemDTO);
        }

        orderQRCodeDTO.setItems(result);
        return orderQRCodeDTO;
    }
}
